package com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.dataobject.Order;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.dataobject.TransactionLog;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.dto.OrderDTO;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.mapper.OrderMapper;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.mapper.TransactionLogMapper;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.message.OrderMessage;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.message.OrderSource;
import com.ziyucoding.springboot.labs.lab3.sca.rocketmqdemo.dtd.order.service.OrderService;
import org.apache.rocketmq.client.exception.MQClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单服务实现类
 *
 * @author ziyucoding
 * @date 2023-04-02
 **/
@Service
public class OrderServiceImpl implements OrderService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderSource orderSource;

    @Autowired
    private TransactionLogMapper transactionLogMapper;

    Snowflake snowflake = new Snowflake(1, 1);

    /**
     * 执行本地事务时调用，将订单数据和事务日志写入本地数据库
     *
     * @param orderDTO
     * @param transactionId
     * @return void
     */
    @Transactional
    @Override
    public void createOrder(OrderDTO orderDTO, String transactionId) {

        // 1.创建订单
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        orderMapper.insert(order);

        // 2.写入事务日志
        TransactionLog log = new TransactionLog();
        log.setId(transactionId);
        log.setBusiness("order");
        log.setForeignKey(String.valueOf(order.getId()));
        transactionLogMapper.insert(log);

        logger.info("订单创建完成。{}", orderDTO);
    }

    /**
     * 前端调用，只用于向RocketMQ发送事务消息
     *
     * @param order
     * @return void
     */
    @Override
    public void createOrder(OrderDTO order) throws MQClientException {
        order.setId(snowflake.nextId());
        order.setOrderNo(snowflake.nextIdStr());

        // 创建 Message
        OrderMessage message = new OrderMessage();
        BeanUtils.copyProperties(order, order);
        // 创建 Spring Message 对象
        org.springframework.messaging.Message<OrderMessage> springMessage = MessageBuilder
                .withPayload(message)
                .setHeader("order", JSON.toJSONString(order))
                .build();
        // 发送消息
        boolean sendResult = orderSource.orderOutput().send(springMessage);
        logger.info("[send][发送消息完成, 结果 = {}]", sendResult);
    }
}
